package com.woniu.service.mallSystem.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniu.mapper.mallSystem.CommodityMapper;
import com.woniu.model.gh.common.Result;
import com.woniu.model.mallSystem.dto.CommodityESDto;
import com.woniu.model.mallSystem.dto.CommodityQueryDto;
import com.woniu.model.mallSystem.entity.Commodity;
import com.woniu.model.mallSystem.vo.CommodityVo;
import com.woniu.model.mallSystem.vo.PageVo;
import com.woniu.service.mallSystem.ICommodityService;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author Lzj
 * @since 2023-10-19
 */
@Service
public class CommodityServiceImpl extends ServiceImpl<CommodityMapper, Commodity> implements ICommodityService {

    @Autowired
    private CommodityMapper commodityMapper;
    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Override
    public PageInfo<CommodityVo> findAllCommodities(int pageNum, int pageSize, Map<String, Object> condition) {
        PageHelper.startPage(pageNum, pageSize);
        List<CommodityVo> commodityList = commodityMapper.findByCondition(condition);
        return new PageInfo<>(commodityList);
    }

    /**
     *
     * 高级筛选
     */
    @Override
    public PageVo<Commodity> conditionQuery(Integer pageNum, Integer pageSize, CommodityQueryDto commodityQueryDto) {

        LambdaQueryWrapper<Commodity> wrapper = new LambdaQueryWrapper<>();
        // 设置查询条件动态拼接
//        wrapper.like(commodityQueryDto.getName() != null && commodityQueryDto.getName() !="",
//                Commodity::getName, commodityQueryDto.getName());
//        wrapper.eq(commodityQueryDto.getCategoryId() != null,
//                Commodity::getTCategoryId, commodityQueryDto.getCategoryId());
//        wrapper.eq(commodityQueryDto.getStatus() != null,
//                Commodity::getStatus, commodityQueryDto.getStatus());
//        wrapper.like(commodityQueryDto.getCode() != null && commodityQueryDto.getCode() !="",
//                Commodity::getCode, commodityQueryDto.getCode());
//        wrapper.ge(commodityQueryDto.getHighPrice() != null,
//                Commodity::getPrice, commodityQueryDto.getLowPrice().doubleValue());
//        wrapper.le(commodityQueryDto.getHighPrice() != null,
//                Commodity::getPrice, commodityQueryDto.getHighPrice().doubleValue());

        if (commodityQueryDto.getName() != null && commodityQueryDto.getName() !="") {
            wrapper.like(Commodity::getName, commodityQueryDto.getName());
        }
        if (commodityQueryDto.getCategoryId() != null) {
            wrapper.eq(Commodity::getTCategoryId, commodityQueryDto.getCategoryId());
        }
        if (commodityQueryDto.getStatus() != null) {
            wrapper.eq(Commodity::getStatus, commodityQueryDto.getStatus());
        }
        if (commodityQueryDto.getCode() != null && commodityQueryDto.getCode() !="") {
            wrapper.like(Commodity::getCode, commodityQueryDto.getCode());
        }
        if (commodityQueryDto.getLowPrice() != null) {
            wrapper.ge(Commodity::getPrice, commodityQueryDto.getLowPrice().doubleValue());
        }
        if (commodityQueryDto.getHighPrice() != null) {
            wrapper.le(Commodity::getPrice, commodityQueryDto.getHighPrice().doubleValue());
        }
        Page<Commodity> commodityPage = commodityMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        return new PageVo<>(commodityPage.getRecords(),commodityPage.getTotal());
    }

    /**
     *
     * 批量下架
     */

    public Result offline(String[] ids) {
        // 将状态设置为下架（0）
        int status = 0;
        // 批量更新商品状态
        commodityMapper.deleteById(ids);
        return  Result.ok();
    }

    /**
     * es高亮搜索
     */
    @Override
    public Map<String, Object> search(String keyword, Integer pageNum, Integer pageSize) {
        // 条件构造器
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        builder.withQuery(QueryBuilders.multiMatchQuery(keyword, "name", "title", "subhead", "details"));
        builder.withPageable(PageRequest.of(pageNum - 1, pageSize));
        // 设置高亮
        HighlightBuilder.Field[] fields = new HighlightBuilder.Field[1];
        fields[0] = new HighlightBuilder.Field("name")
                .preTags("<span style='background-color:Crimson; color:White'>")
                .postTags("</span>");
        builder.withHighlightFields(fields);
        // 执行搜索
        SearchHits<Commodity> searchHits = elasticsearchRestTemplate.search(builder.build(), Commodity.class);
        // 处理结果
        List<Commodity> commodityList = searchHits.getSearchHits().stream().map(searchHit -> {
            Commodity commodity = searchHit.getContent();
            // 获取高亮字段
            List<String> stringList = searchHit.getHighlightField("name");
            if (!CollectionUtils.isEmpty(stringList)) {
                StringBuffer sb = new StringBuffer();
                for (String str : stringList) {
                    sb.append(str);
                }
                commodity.setName(sb.toString()); // 设置高亮结果
            }
            return commodity;
        }).collect(Collectors.toList());
        // 返回结果
        Map<String, Object> map = new HashMap<>();
        map.put("list", commodityList);
        map.put("total", searchHits.getTotalHits());
        return map;
    }

    @Override
    public PageInfo<CommodityVo> advancedQuery(int pageNum, int pageSize, Map<String, Object> advanceCondition) {
        PageHelper.startPage(pageNum, pageSize);
        List<CommodityVo> commodityList = commodityMapper.advanceCondition(advanceCondition);
        return new PageInfo<>(commodityList);
    }

    @Override
    public PageInfo<CommodityVo> listByElasticSearch(int pageNum, int pageSize, CommodityESDto commodityESDto) {
        PageHelper.startPage(pageNum, pageSize);

        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();

        // 商品名称
        if (StringUtils.hasLength(commodityESDto.getName())){
            builder.withQuery(QueryBuilders.multiMatchQuery(commodityESDto.getName(),
                    "name", "title", "subhead", "details"));
        }
        // 商品编码
        if (StringUtils.hasLength(commodityESDto.getCode())){
            builder.withQuery(QueryBuilders.matchQuery("code",
                    commodityESDto.getCode()));
        }

        // 商品状态
        if (commodityESDto.getStatus() != null){
            builder.withQuery(QueryBuilders.matchQuery("status",
                    commodityESDto.getStatus()));
        }

        // 商品分类
        if (commodityESDto.getCategoryId() != null){
            builder.withQuery(QueryBuilders.multiMatchQuery(commodityESDto.getCategoryId(),
                    "parentId", "typeId"));
        }

        SearchHits<CommodityVo> hits = elasticsearchRestTemplate.search(builder.build(), CommodityVo.class);
        List<CommodityVo> commodityVoList =
                hits.stream().map(e -> e.getContent()).collect(Collectors.toList());

        return new PageInfo<>(commodityVoList);
    }

    /**
     *
     * 分页全文搜索
     */



}
